package titt.util.io.loader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import titt.util.JAR;

public class BINFileLoader implements FileStreamLoader {
	
	private final FileStreamLoader debugLoader;
	private final String base;
	
	public BINFileLoader(String base) {
		this(base, new HDDFileLoader());
	}
	
	public BINFileLoader(String base, FileStreamLoader debugLoader) {
		if(base.endsWith("/"))
			base = base.substring(0, base.length()-1);
		this.base = base;
		this.debugLoader = debugLoader;
	}
	
	public BINFileLoader() {
		this("");
	}

	public FileStream loadFileStream(String filename) {
		URL u = getClass().getResource(base + filename);

		if(u == null)
			return null;

		try {
			return new FileStream(filename, this, new File(u.getPath()));
		}
		catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	public InputStream loadStream(String filename) {
		return getClass().getResourceAsStream(base + filename);
	}

	
	@Override
	public List<FileStream> loadDirectoryStream(String dirname) {
		dirname = base + dirname;
				
		ArrayList<FileStream> files = new ArrayList<FileStream>();

		if(!JAR.get().isJAR()) {
			
			dirname = dirname.startsWith("/")? dirname : "/" + dirname;
			String[] bins = System.getProperties().getProperty("java.class.path").split("\\:");
			HashSet<String> uniqueBins = new HashSet<String>();

			for(String bin : bins)
				if(new File(bin).isDirectory())
					uniqueBins.add(bin);
			
			for(String bin : uniqueBins)
				files.addAll(debugLoader.loadDirectoryStream(bin + dirname));

			return files;
		}
		
		try {
			JarFile jf = new JarFile(JAR.get().getRunningJarName());
			Enumeration<JarEntry> entries = jf.entries();
			while(entries.hasMoreElements()) {
				String name = entries.nextElement().getName();
				name = name.startsWith("/")? name : "/"+name;
				if(name.startsWith(dirname))
					files.add(loadFileStream(name));
			}
		} 
		catch (IOException e) {
		}
		
		return files;
	}

}
